#include "LogicSystem.h"
#include "io_thread.h"
#include "session.h"
#include <iostream>
#include "global.h"
#include "MsgNode.h"
LogicSystem::LogicSystem(): 
    _running(true)
{
    _worker_thread = std::thread (&LogicSystem::DealMsg, this);
    RegisterCallBacks();
}

LogicSystem::~LogicSystem() {
    Stop();
}

void LogicSystem::Stop() {
    _running = false;
    _queue_cv.notify_all();
    _worker_thread.join();
}

void LogicSystem::PostMsgToQue(std::shared_ptr<LogicNode> msg) {
    try {
        if (!msg || !msg->_session || !msg->_recv_node) {
            std::cerr << "Invalid message or session in PostMsgToQue" << std::endl;
            return;
        }

        {
            std::lock_guard<std::mutex> lock(_queue_mutex);
            _msg_que.push(msg);
        }
        _queue_cv.notify_one();
    } catch (const std::exception& e) {
        std::cerr << "Exception in PostMsgToQue: " << e.what() << std::endl;
    }
}

void LogicSystem::DealMsg() {
	for (;;) {
		std::unique_lock<std::mutex> unique_lk(_queue_mutex);
		
		try {
			//判断队列为空则用条件变量阻塞等待，并释放锁
			while (_msg_que.empty() && _running) {
				_queue_cv.wait(unique_lk);
			}

			//如果已经停止运行且队列为空，则退出
			if (!_running && _msg_que.empty()) {
				break;
			}
		} catch (const std::exception& e) {
			std::cerr << "Exception in DealMsg loop: " << e.what() << std::endl;
			continue;
		}
	
		//处理消息
		if (!_msg_que.empty()) {
			auto msg_node = _msg_que.front();
			_msg_que.pop();  // 先把消息从队列中移除

			if (!msg_node) {
				std::cerr << "[Error] msg_node is nullptr" << std::endl;
			} else if (!msg_node->_recv_node) {
				std::cerr << "[Error] msg_node->_recv_node is nullptr" << std::endl;
			} else if (!msg_node->_session) {
				std::cerr << "[Error] msg_node->_session is nullptr" << std::endl;
			} else {
				std::cout << "recv_msg id is " << msg_node->_recv_node->_msg_id << std::endl;
				auto call_back_iter = _fun_callbacks.find(msg_node->_recv_node->_msg_id);
				if (call_back_iter != _fun_callbacks.end()) {
					try {
						call_back_iter->second(msg_node->_session, msg_node->_recv_node->_msg_id,
							std::string(msg_node->_recv_node->_data.get(), msg_node->_recv_node->_cur_len));
					} catch (const std::exception& e) {
						std::cerr << "Error processing message: " << e.what() << std::endl;
					}
				}
			}
		}
	}
}

void LogicSystem::RegisterCallBacks() {
    _fun_callbacks[TEST] = 
        [this](std::shared_ptr<Session> session, size_t msg_id, std::string msg_data) {
            // 直接调用成员函数，参数传递更直观
            this->HelloWordCallBack(session, msg_id, msg_data);
        };
	_fun_callbacks[MSG_PING] =
		[this](std::shared_ptr<Session> session, size_t msg_id, std::string msg_data){
			this->PingCallBack(session, msg_id, msg_data);
		};
}

void LogicSystem::HelloWordCallBack(std::shared_ptr<Session> session, size_t msg_id, std::string msg_data) {
	Json::Reader reader;
	Json::Value root;
	reader.parse(msg_data, root);
	//std::cout<< "hello from logic fun" <<std::endl;
	std::cout << "recevie msg id  is " << root["id"].asInt() << " msg data is "
		<< root["data"].asString() << std::endl;
	root["data"] = "server has received msg, msg data is " + root["data"].asString();
	std::string return_str = root.toStyledString();
	session->Send(return_str, root["id"].asInt());
}

void LogicSystem::PingCallBack(std::shared_ptr<Session> session, size_t msg_id, std::string msg_data) {
    // 收到客户端的 PING，回复一个 PONG
	std::cout << "Received PING from Session[" << session->GetFd() << "]. Sending PONG." << std::endl;
	
	// 构造一个简单的 PONG 响应，包含服务器时间戳
	// time_t now = time(nullptr);
	// std::string pong_data = "Server time: " + std::to_string(now);

	// 发送 PONG 响应
	session->Send("", MSG_PONG);
	std::cout << "PONG sent to Session[" << session->GetFd() << "]" << std::endl;

	session->update_active_time();
}